package com.wealth.scsj.b_app.view.activity.storesettingmodel;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.vondear.rxtools.RxPermissionsTool;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.wealth.scsj.b_app.R;
import com.wealth.scsj.b_app.base.UpdateUserProfilePictureBase;
import com.wealth.scsj.b_app.bean.UpdateUserProfilePictureBean;
import com.wealth.scsj.b_app.customview.dialog.ActionSheetDialog;
import com.wealth.scsj.b_app.presenter.UpdateUserProfilePicturePresenter;
import com.wealth.scsj.b_app.utils.CropCircleTransformation;
import com.wealth.scsj.b_app.utils.SkipUtils;
import com.wealth.scsj.b_app.view.activity.BaseActivity;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;

/**
 * 门店设置 主页面
 *
 * @author qxp
 */
public class StoreSettingPageActivity extends BaseActivity implements View.OnClickListener , UpdateUserProfilePictureBase.IView {

    private TextView mBusinessStateTv, mBusinessDataTv, mShopHeadTv, mShopNoticesTv,
            mShopAddressTv, mContactPhoneNumberTv, mDestributionInformationTv, mContactBusinessChargeTv
            ,mTvTopTittle;
    private RelativeLayout mBusinessStateRl, mBusinessDataRl, mShopHeadRl, mShopNoticesRl, mShopAddressRl,
            mShopContactPhoneRl, mShopDestriInforRl, mShopCircleChargeRl;
    private Button mSaveChangeBtn;
    private ImageView mBtnBack,mHeadIconIv;
    private Uri resultUri;

    private UpdateUserProfilePicturePresenter mUpdateUserProfilePicturePresenter;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_store_setting_page);

        mUpdateUserProfilePicturePresenter =new UpdateUserProfilePicturePresenter(this);


    }

    @Override
    protected void initView() {

        mTvTopTittle =findViewById(R.id.tv_top_tittle);

        mBusinessStateTv = findViewById(R.id.business_state_tv);
        mBusinessDataTv = findViewById(R.id.business_data_tv);
        mShopNoticesTv = findViewById(R.id.shop_notices_tv);
        mShopAddressTv = findViewById(R.id.shop_address_tv);
        mContactPhoneNumberTv = findViewById(R.id.contact_phone_number_tv);
        mDestributionInformationTv = findViewById(R.id.destribution_information_tv);
        mContactBusinessChargeTv = findViewById(R.id.contact_business_charge_tv);

        mBusinessStateRl = findViewById(R.id.business_state_rl);
        mBusinessDataRl = findViewById(R.id.business_data_rl);
        mShopHeadRl = findViewById(R.id.shop_head_rl);
        mShopNoticesRl = findViewById(R.id.shop_notices_rl);
        mShopAddressRl = findViewById(R.id.shop_address_rl);
        mShopContactPhoneRl = findViewById(R.id.shop_contact_phone_rl);
        mShopDestriInforRl = findViewById(R.id.shop_destri_infor_rl);
        mShopCircleChargeRl = findViewById(R.id.shop_circle_charge_rl);

        mSaveChangeBtn = findViewById(R.id.save_change_btn);

        mBtnBack =findViewById(R.id.btn_back);

        mHeadIconIv =findViewById(R.id.head_icon_iv);
    }

    @Override
    protected void initListener() {
        mBusinessStateRl.setOnClickListener(this);
        mBusinessDataRl.setOnClickListener(this);
        mShopHeadRl.setOnClickListener(this);
        mShopNoticesRl.setOnClickListener(this);
        mShopAddressRl.setOnClickListener(this);
        mShopContactPhoneRl.setOnClickListener(this);
        mShopDestriInforRl.setOnClickListener(this);
        mShopCircleChargeRl.setOnClickListener(this);

        mSaveChangeBtn.setOnClickListener(this);
        mBtnBack.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        //TODO

        mTvTopTittle.setText("门店设置");

        Resources r =this.getResources();
        resultUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceTypeName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceEntryName(R.drawable.ic_launcher_background));
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.business_state_rl:
                SkipUtils.toBusinessStatePage(StoreSettingPageActivity.this);
                break;
            case R.id.business_data_rl:
                //TODO  弹窗形式
                break;
            case R.id.shop_head_rl:
                RxPermissionsTool.with(StoreSettingPageActivity.this)
                        .addPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(android.Manifest.permission.CAMERA)
                        .initPermission();
                initChooseDialog();
                break;
            case R.id.shop_notices_rl:
                SkipUtils.toShopCommonPage(StoreSettingPageActivity.this,1);
                break;
            case R.id.shop_address_rl:
                SkipUtils.toShopAddressPage(StoreSettingPageActivity.this);
                break;
            case R.id.shop_contact_phone_rl:
                SkipUtils.toShopCommonPage(StoreSettingPageActivity.this,2);
                break;
            case R.id.shop_destri_infor_rl:
                SkipUtils.toDistributionInformationPage(StoreSettingPageActivity.this);
                break;
            case R.id.shop_circle_charge_rl:
                SkipUtils.toCircleMasterDetailsPage(StoreSettingPageActivity.this);
                break;
            case R.id.save_change_btn:
                break;
            case R.id.btn_back:
                finish();
                break;
        }
    }
    /**
     * 拍照选择弹出框
     */
    private void initChooseDialog() {

        new ActionSheetDialog(StoreSettingPageActivity.this).builder().setTitle("请选择图片", 16)
                .addSheetItem("摄像头拍摄", ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        RxPhotoTool.openCameraImage(StoreSettingPageActivity.this);
                    }
                })
                .addSheetItem("从相册获取", ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
                    public void onClick(int which) {
                        RxPhotoTool.openLocalImage(StoreSettingPageActivity.this);
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                Glide.with(this).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.RESULT).
                        bitmapTransform(new CropCircleTransformation(this)).
                        thumbnail(0.5f).
                        placeholder(R.drawable.ic_launcher_background).
                        priority(Priority.LOW).
                        error(R.drawable.ic_launcher_background).
                        fallback(R.drawable.ic_launcher_background).
                        into(mHeadIconIv);
//                RequestUpdateAvatar(new File(RxPhotoTool.getRealFilePath(mContext, RxPhotoTool.cropImageUri)));
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    roadImageView(resultUri, mHeadIconIv);
                    RxSPTool.putContent(this, "AVATAR", resultUri.toString());
                    //接口请求
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("userId", "test2");
                    jsonObject.put("resourceInfoId", "0437b0e0-793d-11e8-afb7-70106fb15682");//resultUri.toString()
                    jsonObject.put("heightFrameCapture", 20);
                    jsonObject.put("widthFrameCapture", 20);
                    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
                    mUpdateUserProfilePicturePresenter.deliverUpdateUserProfilePictureData(body);
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        Glide.with(this).
                load(uri).
                diskCacheStrategy(DiskCacheStrategy.RESULT).
                bitmapTransform(new CropCircleTransformation(this)).
                thumbnail(0.5f).
                placeholder(R.drawable.ic_launcher_background).
                priority(Priority.LOW).
                error(R.drawable.ic_launcher_background).
                fallback(R.drawable.ic_launcher_background).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }

    @Override
    public void showSuccessMsg(String s, UpdateUserProfilePictureBean bean) {
        Toasty.success(this,"成功了");
    }

    @Override
    public void showErrorMsg(String s) {

    }
}
